<template>
  <div class="container">
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <el-form-item label="手机" prop="mobile">
        <el-input
            v-model="form.mobile"
            placeholder="请填写手机"
            clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="realName">
        <el-input
            v-model="form.realName"
            placeholder="请填写姓名"
            clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="mail">
        <el-input
            v-model="form.mail"
            placeholder="请填写邮箱"
            clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="身份证" prop="idCard">
        <el-input
            v-model="form.idCard"
            placeholder="请填写身份证"
            clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <upload-image
            v-model="form.avatar"
            :preview="avatarPreview"
            @update:value="form.avatar = $event"
            @update:preview="avatarPreview = $event"
            :data="{
            tplCode: ossTplCode,
            prefix: 'pic/user',
            renamed: true,
          }"
            :isCropper="true"
        />
      </el-form-item>
      <el-form-item label="身份证正面" prop="idCardFront">
        <upload-image
            v-model="form.idCardFront"
            :preview="idCardFrontPreview"
            @update:value="form.idCardFront = $event"
            @update:preview="idCardFrontPreview = $event"
            :data="{
            tplCode: ossTplCode,
            prefix: 'pic/user',
            renamed: true,
          }"
            :isCropper="true"
        />
      </el-form-item>
      <el-form-item label="身份证背面" prop="idCardBack">
        <upload-image
            v-model="form.idCardBack"
            :preview="idCardBackPreview"
            @update:value="form.idCardBack = $event"
            @update:preview="idCardBackPreview = $event"
            :data="{
            tplCode: ossTplCode,
            prefix: 'pic/user',
            renamed: true,
          }"
            :isCropper="true"
        />
      </el-form-item>
      <el-form-item label="所在省市区：" prop="address">
        <el-cascader
            v-model="selectedOptions"
            placeholder="请填写所在省市区"
            :options="form.cascaderOptions"
            :props="defaultProps"
        ></el-cascader>
      </el-form-item>
      <el-form-item
          label="所属部门"
          prop="departmentIds">
        <el-tree
            ref="departmentTree"
            :data="form.departments"
            show-checkbox
            node-key="id"
            :default-checked-keys="form.departmentIds"
            :props="defaultProps"
        >
        </el-tree>
      </el-form-item>
      <el-form-item label="所属职位" prop="positionIds">
        <el-select
            v-model="form.positionIds"
            placeholder="请填写所属职位"
            class="handle-select mr10"
            clearable
            filterable
            multiple
        >
          <el-option
              v-for="item in form.positions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" size="small" @click="saveEdit"
        >保存
        </el-button
        >
        <el-button size="small" @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {userDetailExtendApi, userEditApi, userSaveApi} from "../../../api/mgt/power/user";
import {regionListEnabledApi} from "../../../api/setup/region";
import {departmentListByUserIdApi} from "../../../api/mgt/power/department";
import {positionListByUserIdApi} from "../../../api/mgt/power/position";

import {createObjectBase, deepCopy, getTreeByCheck, getSelectIds, logoutClear} from "@/utils";

const obj = {
  //信息
  id: "",
  mobile: "",
  realName: "",
  mail: "",
  avatar: "",
  idCard: "",
  idCardFront: "",
  idCardBack: "",
  sex: "MALE",
  departmentIds: [],
  positionIds: [],
};
const mgtOssTplCode = process.env.VUE_APP_MGT_OSS_TPL_CODE;
export default {
  data() {
    const checkPhone = (rule, value, callback) => {
      const reg = /^1[3|4|5|7|8][0-9]{9}$/;
      if (!value) {
        return callback(new Error("手机不能为空"));
      }
      if (!Number.isInteger(+value)) {
        callback(new Error("请填写数字值"));
      } else {
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("手机格式不正确"));
        }
      }
    };
    const checkEmail = (rule, value, callback) => {
      const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (!value) {
        return callback(new Error("邮箱不能为空"));
      } else {
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("请填写正确的邮箱格式"));
        }
      }
    };
    const checkAddress = (rule, value, callback) => {
      if (!this.selectedOptions.length) {
        callback(new Error('请填写所在省市区'))
      } else {
        callback()
      }
    };
    const checkDepartment = (rule, value, callback) => {
      let arr = this.$refs.departmentTree.getCheckedKeys()
      if (arr.length == 0 || !arr) {
        callback(new Error("请填写所属部门"));
      } else {
        callback();
      }
    };
    return {
      ossTplCode: mgtOssTplCode,
      form: deepCopy(obj),
      defaultProps: {
        children: "children",
        value: "name",
        label: "name",
      },
      avatarPreview: "",
      idCardFrontPreview: "",
      idCardBackPreview: "",
      selectedOptions: [],
      rules: {
        mobile: [{required: true, validator: checkPhone, trigger: "change"}],
        realName: [
          {required: true, message: "请填写姓名", trigger: "change"},
          {max: 20, message: "长度不能超过20个字符", trigger: "change"},
        ],
        mail: [
          {required: true, validator: checkEmail, trigger: "change"},
          {max: 50, message: "长度不能超过50个字符", trigger: "change"},
        ],
        idCard: [
          {max: 18, message: "长度不能超过18个字符", trigger: "change"},
        ],
        address: [
          {required: true, validator: checkAddress, trigger: "change"},
        ],
        departmentIds: [
          {required: true, validator: checkDepartment, trigger: "change"},
        ],
        positionIds: [
          {required: true, message: "请填写所属职位", trigger: "change"},
        ],
      },
    };
  },
  methods: {
    // 编辑操作
    getDetail(id) {
      if (!id) {
        if (this.$refs.form != undefined) {
          this.$refs['form'].resetFields();
          this.avatarPreview = "";
          this.idCardBackPreview = "";
          this.idCardFrontPreview = "";
        }
        regionListEnabledApi().then((res) => {
          this.form.cascaderOptions = res?.bizData;
        });
        departmentListByUserIdApi().then((res) => {
          this.form.departments = res?.bizData;
        });
        positionListByUserIdApi().then((res) => {
          this.form.positions = res?.bizData;
        });
      } else {
        Promise.all([
          regionListEnabledApi(),
          departmentListByUserIdApi({userId: id}),
          positionListByUserIdApi({userId: id}),
          userDetailExtendApi({id}),
        ]).then(([regions, departments, positions, userDetail]) => {
          let userData = userDetail?.bizData;
          if (userData.avatarStr != null && userData.avatarStr != '') {
            this.avatarPreview = userData.avatarStr;
          }
          if (userData.idCardBackStr != null && userData.idCardBackStr != '') {
            this.idCardBackPreview = userData.idCardBackStr;
          }
          if (userData.idCardFrontStr != null && userData.idCardFrontStr != '') {
            this.idCardFrontPreview = userData.idCardFrontStr;
          }
          const formData = Object.assign(deepCopy(userData), {
            departments: departments?.bizData,
            departmentIds: [],
            positions: positions?.bizData,
            positionIds: [],
            cascaderOptions: regions?.bizData,
          });
          if (formData.departments !== null) {
            formData.departmentIds = getTreeByCheck(formData.departments).map(item => item.id);
          }
          if (formData.positions !== null) {
            formData.positionIds = formData.positions.filter(item => item.checked).map(item => item.id);
          }
          this.selectedOptions[0] = formData.province;
          this.selectedOptions[1] = formData.city;
          this.selectedOptions[2] = formData.district;
          this.form = formData;
        });
      }
    },
    saveEdit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const data = createObjectBase(this.form, Object.keys(obj));
          const {id} = data;
          const {departmentTree} = this.$refs;
          data.departmentIds = getSelectIds(departmentTree);
          data.province = this.selectedOptions[0];
          data.city = this.selectedOptions[1];
          data.district = this.selectedOptions[2];
          const fn = id ? userEditApi : userSaveApi;
          fn(data).then((res) => {
            if (id === this.$store.state.userInfo.id) {
              logoutClear();
            } else {
              this.goBack();
            }
          });
        } else {
          return false;
        }
      });
    },
    goBack() {
      this.$router.goPage({
        path: "/user/page",
      });
    },
  }
  ,
  created() {
    const {id} = this.$route.query;
    this.getDetail(id);
  }
  ,
}
;
</script>
